package cn.topcodes.tcsf.app.web.controller.userend.interceptor;

import cn.topcode.unicorn.utils.RenderUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.app.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Unicorn on 2017/10/16.
 */
public class UserendAuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AppUserService appUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            IgnoreUserendAuth auth = ((HandlerMethod) handler).getMethodAnnotation(IgnoreUserendAuth.class);
            if (auth == null) {
                String token = (String) request.getSession().getAttribute("token");
                if (StringUtil.isBlank(token) || !appUserService.isOnline(token)) {
                    response.sendRedirect("/userend/login");
                    return false;
                }
            }
        }
        return super.preHandle(request, response, handler);
    }
}
